package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Audit;
import com.kang.pojo.Cruise;
import com.kang.pojo.Organization;
import com.kang.pojo.PurchaseItem;
import com.kang.pojo.PurchaseOrder;
import com.kang.service.AssistService;
import com.kang.service.AuditService;
import com.kang.service.PurchaseAgentService;
import com.kang.service.PurchaseOrderService;
import com.kang.service.SupplierService;
import com.kang.service.WarehouseService;
import com.kang.until.PurchaseAgentExcelExport;
import com.kang.until.PurchaseAgentPDF;
import com.vonechina.entity.page.PurchaseAgentPage;
import com.vonechina.entity.page.PurchaseItemPage;

/**
 * 待采购物资控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("purchaseAgent")
@SessionAttributes({ "purchaseAgentPage" })
public class PurchaseAgentController extends com.kang.controller.Controller {
	/**
	 * 代采购物资服务层
	 */
	@Resource
	private PurchaseAgentService purchaseService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 供应商服务层
	 */
	@Resource
	private SupplierService supplierService;
	/**
	 * 采购订单服务层
	 */
	@Resource
	private PurchaseOrderService orderService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 审核服务层
	 */
	@Resource
	private AuditService auditService;

	/**
	 * 待采购物资分页查看接口
	 * 
	 * @param session
	 * @param model
	 * @param purchaseAgentPage
	 *            搜索条件自动封装实体类
	 * @return 返回jsp页面
	 */
	@RequestMapping("listPurchaseAgent")
	public String listPurchaseAgent(HttpSession session, Model model, PurchaseAgentPage purchaseAgentPage) {
		initRight(session);
		if (checkRight("查看待采购物资") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("itemList", purchaseService.listPurchaseItem(purchaseAgentPage));
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("isAddPurchaseOrder", checkRight("新增采购订单") == SUCCESS);
		purchaseAgentPage.setPageUrl("purchaseAgent/listPurchaseAgent.do");
		model.addAttribute("page", purchaseAgentPage);
		return "business/purchaseAgent/listPurchaseAgent";
	}

	/**
	 * 前往新增采购订单页面
	 * 
	 * @param session
	 * @param model
	 * @return 返回jsp页面
	 */
	@RequestMapping("toAddPurchaseOrder")
	public String toAddPurchaseOrder(HttpSession session, Model model) {
		initRight(session);
		if (checkRight("新增采购订单") != SUCCESS) {
			return "basic/noRight";
		}
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("supplierList", supplierService.listAllSupplier());// 查询供应商
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "business/purchaseAgent/addPurchaseOrder";
	}

	/**
	 * 新增采购订单时查询符合条件物品
	 * 
	 * @param page
	 *            搜索条件自动封装
	 * @return 返回josn字符串
	 */
	@RequestMapping("listNotAddItem")
	@ResponseBody
	public String listNotAddItem(PurchaseItemPage page) {
		AjaxResult result = new AjaxResult();
		result.setRows(purchaseService.listPurchaseItemNotIn(page));
		result.setTotal(page.getRows());
		return JSON.toJSONString(result);
	}

	/**
	 * 新增采购订单
	 * 
	 * @param session
	 * @param order
	 *            采购订单实体类自动封装
	 * @param sourceID
	 *            采购订单物品来源ID数组
	 * @param itemNumber
	 *            采购订单物品采购数量数组
	 * @return 返回json字符串
	 */
	@RequestMapping("addPurchaseOrder")
	@ResponseBody
	public String addPurchaseOrder(HttpSession session, PurchaseOrder order, Integer[] sourceID, Integer[] itemNumber) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (checkRight("新增采购订单") != SUCCESS) {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setOrderNumber(orderService.generatoOrderNo());
		order.setCreatePersonID((Integer) session.getAttribute("userID"));
		order.setLastModifiedID((Integer) session.getAttribute("userID"));
		if (order.getStatus() != null && order.getStatus() == 1) {
			order.setSubmitterID((Integer) session.getAttribute("userID"));
			order.setCommitTime(new Date());
		}
		int a = orderService.insertOrder(order);
		if (a > 0) {
			if (order.getStatus() == 1) {
				Audit audit = new Audit();
				audit.setAuditType(2);
				audit.setSourceID(order.getPurchaseOrderID());
				audit.setLastPersonID(userID);
				audit.setMoney("0");
				auditService.addAudit(audit);
				orderService.updateStatus(order.getPurchaseOrderID(), 2);
			}
			orderService.saveOrderItem(order.getPurchaseOrderID(), sourceID, itemNumber);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 导出待采购申请PDF文件
	 * 
	 * @param response     
	 * @param page  页数，通过传入的页数，只打印当前页
	 * @throws Exception
	 */
	@RequestMapping("download")
	public void downloadPDF(HttpServletResponse response, PurchaseAgentPage page)
			throws Exception {
		//System.out.println("==============导出待采购申请PDF文件==============");
		List<PurchaseItem> itemList = purchaseService.listNotInItem(page);
		
		//此方法为直接下载文件
		File file = PurchaseAgentPDF.buildPurchaseAgentPDF(itemList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	/**
	 * 导出待采购物资Excel文件
	 * @param 
	 * @throws
	 */
	@RequestMapping("downloadExcel")
	public void downloadPurchaseAgentExcel(HttpServletRequest request, HttpServletResponse response, PurchaseAgentPage page) 
			throws Exception {
//		System.out.println("======待采购Excel=======");
		
		List<PurchaseItem> piList = purchaseService.listPurchaseItem(page);
		
		//此方法为直接下载文件
		File file = PurchaseAgentExcelExport.buildPurchaseAgentExcel(request, response, piList);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
				    fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
		
	}

}
